package chapter02.item3Builder;

/**
 * Buidler 模式创建对象
 * 可以控制必须与非必须的参数
 * <p>
 * 假设必须参数分别为servingSize， servings， calories;
 */
public class NutritionFacts {

    private final int servingSize;

    private final int servings;

    private final int calories;

    private final int fat;

    private final int sodium;

    private final int carbohydrate;

    public static class Builder {
        // 必须的参数
        private final int servingSize;
        // 必须的参数
        private final int servings;
        // 必须的参数
        private final int calories;

        // 非必须的参数 设置默认值
        private int fat = 0;

        private int sodium = 0;

        private int carbohydrate = 0;

        /**
         * 构造必须的参数
         *
         * @param servingSize
         * @param servings
         * @param calories
         */
        public Builder(int servingSize, int servings, int calories) {
            this.servings = servings;
            this.servingSize = servingSize;
            this.calories = calories;
        }

        public Builder fat(int val) {
            fat = val;
            return this;
        }

        public Builder sodium(int val) {
            sodium = val;
            return this;
        }

        public Builder carbohydrate(int val) {
            carbohydrate = val;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder) {
        this.servingSize = builder.servingSize;
        this.servings = builder.servings;
        this.calories = builder.calories;
        this.fat = builder.fat;
        this.sodium = builder.sodium;
        this.carbohydrate = builder.carbohydrate;
    }


    public static void main(String[] args) {
        NutritionFacts cola = new NutritionFacts.Builder(10, 20, 25).sodium(35).carbohydrate(27).build();

    }
}
